/**
 * ForLoop
 */
public class ForLoop {

    public static void main(String[] args) {
        ForLoop fl = new ForLoop();
        fl.forEachDemo();

        int[] ns = {1,2,3,4,5};
        fl.invertedPrint(ns);

        fl.forEachSum(ns);

        fl.pi();
    }

    //1:for循环写,1到100的和
    private void forDemo() {
        int sum = 0;
        for (int i = 0; i <= 100; i++) {
            sum = sum + i;
        }
        System.out.println("for循环计算的1到100的和是:" + sum);
    }

    // 2:使用for循环对一个整型数组求和
    private void forDemo1() {
        int[] ns = {1,2,3,4,5,6,7};
        int sum = 0;
        for (int i = 0; i < ns.length; i++) {
            System.out.println("i = " + i + " ,ns[i] = " + ns[i]);
            sum = sum + ns[i];
        }
        System.out.println("sum = " + sum);
    }

    // 3:for each
    private void forEachDemo() {
        int[] ns = {1,2,3,4,5,6,7,8,9,10};
        for (int n : ns) {
            System.out.println(n);
        }
    }

    //4: 练习1
    // 使用for循环倒序输出每一个元素
    private void invertedPrint(int[] ns) {
        for (int i = ns.length - 1; i >= 0; i--) {
            System.out.println(ns[i]);
        }
    }
    // 5:练习2
    // 使用for each 对数组每个元素求和
    private void forEachSum(int[] ns) {
        int sum = 0;
        for (int n : ns) {
            sum += n;
        }
        System.out.println("for each对数组求和:" + sum);
    }

    // 6:练习3
    // 计算圆周率
    private void pi() {
        double pi = 0;
        double flag = 1.0;
        for (int i = 1; i < 10000; i += 2, flag = -flag) {
            pi += flag/i;
        }
        System.out.println(pi * 4);
    }
}